<template>
  <a-card :bordered="false">

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button @click="_handleRowMoveUp()" type="primary" icon="up">上移</a-button>
      <a-button @click="_handleRowMoveDown()" type="primary" icon="down">下移</a-button>
      <!--<a-button type="primary" icon="download" @click="handleExportXls('分类字典')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>-->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay" @click="handleMenuClick">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete"/>
            删除
          </a-menu-item>
          <a-menu-item key="2">
            <a-icon type="lock" @click="batchFrozen('2')"/>
            冻结
          </a-menu-item>
          <a-menu-item key="3">
            <a-icon type="unlock" @click="batchFrozen('1')"/>
            解冻
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作
          <a-icon type="menu-fold"/>
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
        selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <a-table
        ref="table"
        size="middle"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :expandedRowKeys="expandedRowKeys"
        @change="handleTableChange"
        @expand="handleExpand"
        v-bind="tableProps"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical"/>
          <a v-if="record.status==1">
            <a-popconfirm title="确定冻结吗?" @confirm="() => handleFrozen(record.id,2,record.username)">
             <a>冻结</a>
            </a-popconfirm>
          </a>
          <a v-if="record.status==2">
            <a-popconfirm title="确定冻结吗?" @confirm="() => handleFrozen(record.id,1,record.username)">
             <a>解冻</a>
            </a-popconfirm>
          </a>
          <a-divider type="vertical"/>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>

    <sysCategory-modal ref="modalForm" @ok="modalFormOk"></sysCategory-modal>
  </a-card>
</template>

<script>

  import { getAction } from '@/api/manage'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import SysCategoryModal from './modules/SysCategoryModal'
  import { frozenCategory } from '../../api/api'
  import { axios } from '../../utils/request'

  export default {
    name: 'SysCategoryList',
    mixins: [JeecgListMixin],
    components: {
      SysCategoryModal,
    },
    data () {
      return {
        description: '分类字典管理页面',
        // 表头
        columns: [
          // {
          //   title: '序号',
          //   align: 'center',
          //   dataIndex: 'rowIndex'
          // },
          {
            title: '类型名称',
            align: 'left',
            dataIndex: 'name'
          },
          // {
          //   title:'类型编码',
          //   align:"left",
          //   dataIndex: 'code'
          // },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            scopedSlots: { customRender: 'action' },
          },
        ],
        defColumns: [],
        url: {
          list: '/sys/category/rootList',
          childList: '/sys/category/childList',
          delete: '/sys/category/delete',
          deleteBatch: '/sys/category/deleteBatch',
          exportXlsUrl: '/sys/category/exportXls',
          importExcelUrl: 'sys/category/importExcel',
        },
        expandedRowKeys: [],
        hasChildrenField: 'hasChild',
        pidField: 'pid',
        dictOptions: {},
        // 父级目录下标数组
        prows: [],
        // 子级目录下标数组
        crows: []
      }
    },
    computed: {
      importExcelUrl () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
      },
      tableProps () {
        let _this = this
        return {
          // 列表项是否可选择
          rowSelection: {
            selectedRowKeys: _this.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
              _this.selectedRowKeys = selectedRowKeys, _this.selectedRows = selectedRows
            },
            onSelect: (record, selected) => {
              _this.record = record, _this.selected = selected
            }
          }
        }
      }
    },
    methods: {
      loadData (arg) {
        // this.prows = []
        if (arg == 1) {
          this.ipagination.current = 1
        }
        this.loading = true
        this.expandedRowKeys = []
        let params = this.getQueryParams()
        return new Promise((resolve) => {
          getAction(this.url.list, params).then(res => {
            if (res.success) {
              let result = res.result
              if (this.prows <= result.records.length) {
                for (let i = 0; i < result.records.length; i++) {
                  this.prows.push(i)
                }
              }
              if (Number(result.total) > 0) {
                this.ipagination.total = Number(result.total)
                this.dataSource = this.getDataByResult(res.result.records)
                resolve()
              } else {
                this.ipagination.total = 0
                this.dataSource = []
              }
            } else {
              this.$message.warning(res.message)
            }
            this.loading = false
          })
        })
      },
      handleMenuClick (e) {
        if (e.key == 1) {
          this.batchDel()
        } else if (e.key == 2) {
          this.batchFrozen(2)
        } else if (e.key == 3) {
          this.batchFrozen(1)
        }
      },
      handleChange (id, oldIndex, newIndex, pid) {
        let that = this
        axios.get('sys/category/changeRowIndex', {
          params: {
            id: id,
            oldIndex: oldIndex,
            newIndex: newIndex,
            pid: pid
          }
        }).then(function (res) {
          if (res.success) {
            that.$message.success(res.message)
            that.loadData()
            that.onClearSelected()
          } else {
            that.$message.warning('操作失败')
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      /** 当前行向上移一位 */
      _handleRowMoveUp () {
        if (!this.selected) {
          return this.$message.warning('请选中行')
        }

        let id = this.selectedRowKeys[0]
        let len = this.selectedRowKeys.length
        let rowIndex = this.record.rowIndex
        let newIndex = rowIndex - 1
        let pid = this.record.pid

        if (len == 1 && rowIndex > 0) {
          this.handleChange(id, rowIndex, newIndex, pid)
        } else if (rowIndex == 0) {
          this.$message.warning('首行无法上移')
        } else if (len > 1) {
          this.$message.warning('只能移动一行')
        }
      },
      /** 当前行向下移一位 */
      _handleRowMoveDown () {
        if (!this.selected) {
          return this.$message.warning('请选中行')
        }

        let id = this.selectedRowKeys[0] // 选中行id
        let len = this.selectedRowKeys.length //选中行数
        let rowIndex = this.record.rowIndex // 当前下标
        let pid = this.record.pid // 是否是父级目录
        let pLen = this.prows.length // 父级菜单长度
        let cLen = this.crows.length  // 子级菜单长度
        let newIndex = rowIndex + 1

        if (len == 1 && rowIndex < pLen - 1) {
          if (pid != 0 && rowIndex >= cLen - 1) {
            return this.$message.warning('最后一行不能下移')
          }

          this.handleChange(id, rowIndex, newIndex, pid)
        } else if (rowIndex == pLen - 1) {
          if (pid != 0 && rowIndex >= cLen - 1) {
            return this.$message.warning('最后一行不能下移')
          }
          this.$message.warning('最后一行不能下移')
        } else if (len > 1) {
          this.$message.warning('只能移动一行')
        }
      },
      batchFrozen: function (status) {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！')
          return false
        } else {
          let ids = ''
          let that = this
          that.selectedRowKeys.forEach(function (val) {
            ids += val + ','
          })
          that.$confirm({
            title: '确认操作',
            content: '是否' + (status == 1 ? '解冻' : '冻结') + '选中目录?',
            onOk: function () {
              frozenCategory({ ids: ids, status: status }).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.message)
                }
              })
            }
          })
        }
      },
      getDataByResult (result) {
        return result.map(item => {
          //判断是否标记了带有子节点
          if (item[this.hasChildrenField] == '1') {
            let loadChild = { id: item.id + '_loadChild', name: 'loading...', isLoading: true }
            item.children = [loadChild]
          }
          return item
        })
      },
      handleExpand (expanded, record) {
        // 判断是否是展开状态
        if (expanded) {
          this.expandedRowKeys.push(record.id)
          this.crows = []
          if (record.children.length > 0 && record.children[0].isLoading === true) {
            let params = this.getQueryParams()//查询条件
            params[this.pidField] = record.id
            getAction(this.url.childList, params).then((res) => {
              if (res.success) {
                let result = res.result
                if (this.crows <= result.length) {
                  for (let i = 0; i < result.length; i++) {
                    this.crows.push(i)
                  }
                }
                if (res.result && res.result.length > 0) {
                  record.children = this.getDataByResult(res.result)
                  this.dataSource = [...this.dataSource]
                } else {
                  record.children = ''
                  record.hasChildrenField = '0'
                }
              } else {
                this.$message.warning(res.message)
              }
            })
          }
        } else {
          let keyIndex = this.expandedRowKeys.indexOf(record.id)
          if (keyIndex >= 0) {
            this.expandedRowKeys.splice(keyIndex, 1)
          }
        }
      },
      handleFrozen: function (id, status) {
        let that = this
        this.$nextTick(()=>{
          frozenCategory({ ids: id, status: status }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          })
        })
      },
      initDictConfig () {
      },
      modalFormOk (formData, arr) {
        if (!formData.id) {
          this.addOk(formData, arr)
        } else {
          this.editOk(formData, this.dataSource)
          this.dataSource = [...this.dataSource]
        }
      },
      editOk (formData, arr) {
        if (arr && arr.length > 0) {
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].id == formData.id) {
              arr[i] = formData
              break
            } else {
              this.editOk(formData, arr[i].children)
            }
          }
        }
      },
      async addOk (formData, arr) {
        if (!formData[this.pidField]) {
          this.loadData()
        } else {
          this.expandedRowKeys = []
          for (let i of arr) {
            await this.expandTreeNode(i)
          }
        }
      },
      expandTreeNode (nodeId) {
        return new Promise((resolve, reject) => {
          this.getFormDataById(nodeId, this.dataSource)
          let row = this.parentFormData
          this.expandedRowKeys.push(nodeId)
          let params = this.getQueryParams()//查询条件
          params[this.pidField] = nodeId
          getAction(this.url.childList, params).then((res) => {
            if (res.success) {
              if (res.result && res.result.length > 0) {
                row.children = this.getDataByResult(res.result)
                this.dataSource = [...this.dataSource]
                resolve()
              } else {
                reject()
              }
            } else {
              reject()
            }
          })
        })
      },
      getFormDataById (id, arr) {
        if (arr && arr.length > 0) {
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].id == id) {
              this.parentFormData = arr[i]
            } else {
              this.getFormDataById(id, arr[i].children)
            }
          }
        }
      },

    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>